import { useEffect } from "react"
import { useState } from "react"
import {applyMiddleware, combineReducers, createStore} from "redux"

function NumberReducer(state = 1, action) {
    switch (action.type) {
        case 'ADD':
            return state + 1

        case 'DEL':
            return state - 1
    
        default:
            return state
    }
}

function InfoReducer(state = {}, action) {
    const {payload = {}} = action
    switch (action.type) {
        case 'SET':
            return {
                ...state,
                ...payload
            }
    
        default:
            return state
    }
}

//注册中间件
function logMiddleware() {
    return (next)=> {
        return (action)=> {
            const {type} = action
            console.log('发生一次action:', type)
            return next(action)
        }
    }
}

//生成Store
const rootMiddleware = applyMiddleware(logMiddleware)
const rootReducer = combineReducers({number: NumberReducer, info: InfoReducer})
const Store = createStore(rootReducer, {number: 1, info: {name: null}}, rootMiddleware)

//使用redux
export default function Index() {
    const [state, changeState] = useState(Store.getState())
    console.log(state)

    useEffect(()=> {
        const unSubscribe = Store.subscribe(()=> {
            changeState(Store.getState())
        })
        return ()=> {unSubscribe()}
    }, [])

    return <div>
         <p>  { state.info.name ? `hello, my name is ${ state.info.name}` : 'what is your name' } ,
           { state.info.mes ? state.info.mes  : ' what do you say? '  } </p>
         《React进阶实践指南》 { state.number } 👍 <br/>
         <button onClick={()=> {Store.dispatch({type: 'ADD'})}}>点赞</button>
         <button onClick={()=> {Store.dispatch({type: 'SET', payload: {name: 'kaho', mes: 'lets learn react'}})}}>修改标题</button>
    </div>
}